package com.rw.coco.handler.message.reply.handler.command;

import com.rw.coco.api.reply.mapper.DiceReply;
import com.rw.coco.handler.message.event.CocoGroupMessageEvent;
import com.rw.coco.handler.message.reply.GroupReplyHandler;
import com.rw.coco.handler.message.reply.handler.command.assistant.CommandMatcher;
import com.rw.coco.handler.message.reply.handler.command.sender.ObSender;
import com.rw.coco.handler.message.reply.handler.command.sender.RASender;
import com.rw.coco.util.DiceRule;
import com.rw.coco.util.config.CocoCommandConfig;
import com.rw.coco.util.config.CocoConfig;
import com.rw.coco.util.config.CocoOption;
import com.rw.tool.util.string.StringUtil;

/**
 * 属性检定暗骰，规则同ra/rc
 * .rah/rch
 */
public class RAHHandler extends GroupReplyHandler {
    private static final int RAH = 0;

    private final CommandMatcher matcher;

    public final boolean funcSwitch;

    public RAHHandler(CocoConfig cocoConfig) {
        CocoCommandConfig cocoCommandConfig = cocoConfig.getCocoCommandConfig();
        CocoOption cocoOption = cocoConfig.getCocoOption();

        String rchCommand = cocoCommandConfig.commandProp.get(CocoCommandConfig.RCH);
        String rahCommand = cocoCommandConfig.commandProp.get(CocoCommandConfig.RAH);
        this.matcher = CommandMatcher.of(rahCommand, rchCommand);
        this.funcSwitch = cocoOption.optionProp.getBoolean(CocoOption.COCO_RAH);
    }

    @Override
    protected boolean groupTrigger(CocoGroupMessageEvent groupEvent) {
        String message = groupEvent.getMessage();
        return funcSwitch && matcher.isMatch(message);
    }

    @Override
    protected void groupHandler(CocoGroupMessageEvent groupEvent) {
        // 分离消息与前缀
        String message = matcher.subTrim(groupEvent.getMessage()).replaceAll("[\\s\\n]", "");
        RASender raSender = new RASender(groupEvent);

        // 根据群房规获取骰点规则
        DiceRule diceRule = raSender.getDiceRule(matcher.isMatch(message, RAH));

        // 处理消息
        String result = raSender.send(message, diceRule);

        // 如果处理消息结果为空，则直接返回
        if (StringUtil.isBlank(result)) {
            return;
        }

        // 发送群聊消息
        DiceReply diceReply = groupEvent.getReplyApi().getDiceReply();
        String propName = raSender.getParseRARule().getName();
        groupEvent.sendBack(diceReply.privateRAReply(groupEvent, propName));

        // 发送私聊消息
        String privateResult = diceReply.privateRAResult(groupEvent, result);
        groupEvent.sendBackSender(privateResult);

        // 对群内所有旁观的人发送结果
        ObSender obSender = new ObSender(groupEvent);
        obSender.sendAllObResult(privateResult);
    }

    @Override
    public int priority() {
        return matcher.priority();
    }
}
